package com.sky.task;

import com.sky.entity.Orders;
import com.sky.service.IOrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @BelongsProject: sky-take-out
 * @Author: XieMingHui
 * @CreateTime: 2023-11-30  15:15
 * @Description: 订单任务
 * @Version: 1.0
 */
@Component
@Slf4j
public class OrderTask {
    @Resource
    private IOrdersService iOrdersService;

    @Scheduled(cron = "0 * * * * ?") //每分钟触发一次
    public void TimeOutNoPayment() {
        log.info("处理超时未付款订单");
        LocalDateTime nowTime = LocalDateTime.now();
        // 设置超时时间为前15分钟下的未支付订单
        LocalDateTime expirationTime = nowTime.minusMinutes(15L);
        iOrdersService.lambdaUpdate()
                .le(Orders::getOrderTime, expirationTime) //小于等于该时间
                .eq(Orders::getStatus, Orders.PENDING_PAYMENT)
                .set(Orders::getStatus, Orders.CANCELLED)
                .set(Orders::getCancelReason, "超时未支付")
                .set(Orders::getCancelTime, nowTime).update();
    }

    //@Scheduled(cron = "0 0 0 * * ? *") //每天00:00触发一次
    @Scheduled(cron ="0 0 0 * * ?")
    public void TimeOutNoDelivery() {
        log.info("处理超时未送达订单");
        LocalDateTime nowTime = LocalDateTime.now();
        iOrdersService.lambdaUpdate()
                .le(Orders::getOrderTime, nowTime) //小于等于该时间
                .eq(Orders::getStatus, Orders.DELIVERY_IN_PROGRESS)
                .set(Orders::getStatus, Orders.COMPLETED)
                .set(Orders::getDeliveryTime, nowTime)
                .set(Orders::getCheckoutTime, nowTime).update();
    }
}
